package com.mes.handler;

import com.mes.data.EmesPBomItem;
import com.mes.manufacture.data.EmesoManuOrder;
import com.mes.manufacture.data.EmesoManuOrderBomItem;
import com.mes.plan.data.EmesPlanOrder;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.Query;
import org.openbravo.dal.service.OBDal;
import org.openbravo.dal.service.OBQuery;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;
import java.math.BigDecimal;
import java.util.List;

/**
 * 下达计划
 */
public class ReleasePlanHandler {
	public JSONObject ReleasePlanOrder(String id) throws Exception {
		JSONObject result = new JSONObject();
		try {
			EmesPlanOrder epo = OBDal.getInstance().get(EmesPlanOrder.class, id);
			result = insertEmesoManuOrder(epo);
			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 主计划下达到车间，车间计划树
	 * @param epo
	 * @return
	 * @throws Exception
	 */
	private JSONObject insertEmesoManuOrder(EmesPlanOrder epo) throws Exception {
		JSONObject result = new JSONObject();
		if (epo.getStatus().equalsIgnoreCase("RELEASE")) {
			result.put("result", false);
			result.put("msg", "计划订单已经下发");
			return result;
		}
		if (!epo.getStatus().equalsIgnoreCase("AUDIT")) {
			result.put("result", false);
			result.put("msg", "计划订单不为审核状态，无法下发");
			return result;
		}
		User user = OBDal.getInstance().get(User.class, SessionInfo.getUserId());
		String clientId = user.getClient().getId();
		String userId = user.getId();
		long qty = epo.getQty();
		EmesPBomItem bomItem = getEmesPBomItem(epo.getProduct().getId(), epo.getEmesPbom().getId());
		BigDecimal pp = null;
		if (bomItem == null) {
			pp = new BigDecimal(qty);
		} else {
			pp = new BigDecimal(qty).divide(bomItem.getItemQty(), 3, BigDecimal.ROUND_HALF_UP);
		}
		String sql = "{call Emes_PLAN_DECOMPSITION(?,?,?,?,?,?)}";
		Query query = OBDal.getInstance().getSession().createSQLQuery(sql);
		query.setString(0, epo.getProduct().getId());
		if (epo.getProduct().getId().equalsIgnoreCase(epo.getEmesPbom().getProduct().getId())) {
			query.setString(1, epo.getEmesPbom().getId());
		} else {
			query.setString(1, "");
		}
		query.setString(2, epo.getId());
		query.setBigDecimal(3, pp);
		query.setString(4, clientId);
		query.setString(5, userId);
		query.executeUpdate();
		result.put("result", true);
		result.put("msg", "计划订单下发成功");
		return result;
	}
	/**
	 * 插入单车间计划BOM项
	 * @param manuOrder
	 * @return
	 */
	private void insertEmesoManuOrderBomItem(EmesoManuOrder manuOrder) {
		// 获取该产品下所有物料BOM项
		String sql = "SELECT epi.* FROM Emes_PBOM_Item epi START WITH epi.emes_pbom_item_id = " + "(select t.emes_pbom_item_id from emes_pbom_item t where t.m_product_id = ?) " + "CONNECT BY PRIOR epi.emes_pbom_item_id = epi.parent_id";
		List<EmesPBomItem> listPBomItem = (List<EmesPBomItem>)
				OBDal.getInstance().getSession().createSQLQuery(sql).addEntity(EmesPBomItem.ENTITY_NAME).setString(0, manuOrder.getProduct().getId()).list();
		for (EmesPBomItem o : listPBomItem) {
			if (!manuOrder.getProduct().getId().equalsIgnoreCase(o.getProduct().getId())) {
				EmesoManuOrderBomItem emob = new EmesoManuOrderBomItem();
				emob.setProduct(o.getProduct());
				emob.setEmesoManuorder(manuOrder);
				emob.setItemQty(o.getItemQty());
				emob.setUom(o.getProduct().getUOM());
				emob.setOrganization(o.getOrganization());
				OBDal.getInstance().save(emob);
			}
		}
	}
	/**
	 * 插入单车间计划的备料清单
	 */
	private EmesPBomItem getEmesPBomItem(String product_ID, String bom_ID) throws Exception {
		OBQuery<EmesPBomItem> query = OBDal.getInstance().createQuery(EmesPBomItem.class, "product.id = :productId and emesPbom.id = :pbomId");
		query.setNamedParameter("productId", product_ID);
		query.setNamedParameter("pbomId", bom_ID);
		List<EmesPBomItem> list = query.list();
		if (list != null && !list.isEmpty()) {
			return list.get(0);
		}
		return null;
	}
}
